package main

import (
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/PuerkitoBio/goquery"
)

var Client http.Client
var wg sync.WaitGroup

func main() {
	// NormalStart()
	// ChannelStart()
	WaitGroupStart()
}

// NormalStart Time 605.707ms
func NormalStart() {
	start := time.Now()
	for i := 0; i < 10; i++ {
		Spider(nil)
	}
	elapsed := time.Since(start)
	fmt.Printf("NormalStart Time %s \n", elapsed)
}

// ChannelStart Time 562.653ms
func ChannelStart() {
	ch := make(chan bool)
	start := time.Now()
	for i := 0; i < 10; i++ {
		go Spider(ch)
	}
	for i := 0; i < 10; i++ {
		// 阻塞直到接收
		<-ch
	}
	elapsed := time.Since(start)
	fmt.Printf("ChannelStart Time %s \n", elapsed)
}

// WaitGroupStart Time 555.1443ms
func WaitGroupStart() {
	start := time.Now()
	wg.Add(10)
	for i := 0; i < 10; i++ {
		go func(i int) {
			// -1
			defer wg.Done()
			Spider(nil)
		}(i)
	}
	// 阻塞
	wg.Wait()
	elapsed := time.Since(start)
	fmt.Printf("WaitGroupStart Time %s \n", elapsed)
}
func Spider(ch chan bool) {
	req, err := http.NewRequest("GET", "https://bksy.cug.edu.cn/index.htm", nil)
	if err != nil {
		fmt.Println("req err", err)
		return
	}
	req.Header.Set("sec-ch-ua-mobile", "?0")
	req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36")
	req.Header.Set("accept", "*/*")
	req.Header.Set("referer", "https://bksy.cug.edu.cn/bkjygk/zyml.htm")
	req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
	req.Header.Set("Connection", "keep-alive")
	resp, err := Client.Do(req)
	if err != nil {
		fmt.Println("client err", err)
	}
	defer resp.Body.Close()
	docDetail, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		fmt.Println("read err", err)
	}
	// body > div.wrap > div.main1.clearfix > div > div.con2l.tg > div > div > div > div:nth-child(1) > div.bd > div > ul
	// body > div.wrap > div.main1.clearfix > div > div.con2l.tg > div > div > div > div:nth-child(1) > div.bd > div > ul > li:nth-child(1) > a.bt
	// body > div.wrap > div.main1.clearfix > div > div.con2l.tg > div > div > div > div:nth-child(1) > div.bd > div > ul > li:nth-child(2) > a.bt
	docDetail.Find("body > div.wrap > div.main1.clearfix > div > div.con2l.tg > div > div > div > div:nth-child(1) > div.bd > div > ul").
		Each(func(i int, s *goquery.Selection) {
			// 通知公告的标题
			s.Find("li > a.bt").Text()
			// fmt.Println(title)
		})
	if ch != nil {
		ch <- true
	}
}
